package com.pay.controller;

import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.SortedMap;
import java.util.TreeMap;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSON;
import com.pay.AliPay.AlipayConfig;
import com.pay.AliPay.AlipayCore;
import com.pay.AliPay.RSA;
import com.pay.WXPay.HttpRequest;
import com.pay.WXPay.RequestHandler;
import com.pay.WXPay.XMLUtil;
import com.pay.utils.MD5;
import com.pay.utils.MessageModel;

@Controller
@RequestMapping("/mobile/pay")
/**
 * 请求支付
 * @author shr
 *
 */
public class MobilePayController {

    private static final String ALIPAY_GATEWAY_NEW = "https://mapi.alipay.com/gateway.do?";

    /**
     * 请求支付
     *
     * @param request
     * @return
     */
    @RequestMapping(value = "/doPay", method = RequestMethod.POST, produces = {"application/json;charset=UTF-8"})
    @ResponseBody
    public String doPay(HttpServletRequest request, HttpServletResponse response, MessageModel model) {
        Map<String, Object> map = new HashMap<String, Object>();
        String order_id = request.getParameter("order_id");
        String pay_method = request.getParameter("pay_method");
        String pay_source = request.getParameter("pay_source");
        String show_url = request.getParameter("show_url");
        String product_name = "商品名称";//订单名称
        String order_price = "";//订单金额
        String order_price_wx = "";//订单金额(wx)
        map.put("id", order_id);
        try {
            order_price = "1";//从数据库查询出的订单价格1元
            int int_order_price = (int) (Double.parseDouble(order_price) * 100);//微信金额 以分为单位
            order_price_wx = Integer.toString(int_order_price);
        } catch (Exception e) {
            model.setCode("0");
            e.printStackTrace();
        }
        if (("wx").equals(pay_method)) {
            // 初始化 RequestHandler
            RequestHandler reqHandler = new RequestHandler(request, response);
            // 拼接参数
            Random random = new Random();
            String noncestr = MD5.GetMD5Code(String.valueOf(random.nextInt(10000)));// 生成随机字符串
            String timestamp = Long.toString(System.currentTimeMillis() / 1000);// 生成1970年到现在的秒数

            reqHandler.setParameter("appid", "");
            reqHandler.setParameter("mch_id", "");// 商户号
            reqHandler.setParameter("nonce_str", noncestr);// 随机字符串
            reqHandler.setParameter("body", product_name);// 商品描述
            reqHandler.setParameter("attach", pay_source);// 支付来源 ios/android
            reqHandler.setParameter("out_trade_no", order_id);// 商家订单号
            reqHandler.setParameter("total_fee", order_price_wx);// 商品金额,以分为单位
            reqHandler.setParameter("spbill_create_ip", request.getRemoteAddr());// 用户的公网IP
            reqHandler.setParameter("notify_url", "http://www.你们的网址.com/mobile/wx/pay");//微信异步通知地址，WXPay.java
            reqHandler.setParameter("trade_type", "APP");
            String requestUrl = reqHandler.getRequestURL(pay_source);
            // 发起统一下单
            String orderUrl = "https://api.mch.weixin.qq.com/pay/unifiedorder";
            String result = HttpRequest.sendPost(orderUrl, requestUrl);
            Map<String, String> orderMap = XMLUtil.doXMLParse(result);
            String prepay_id = orderMap.get("prepay_id");// 预支付ID
            // 调起支付所需参数
            SortedMap<String, String> getPayMap = new TreeMap<String, String>();
            getPayMap.put("appid", "");
            getPayMap.put("partnerid", "");
            getPayMap.put("prepayid", prepay_id);
            getPayMap.put("package", "Sign=WXPay");
            getPayMap.put("noncestr", noncestr);
            getPayMap.put("timestamp", timestamp);
            String sign = reqHandler.createSign(getPayMap, "ios");
            getPayMap.put("sign", sign);
            model.setModel(getPayMap);
            model.setCode("1");
        } else if (("zfb").equals(pay_method)) {
            Map<String, String> getPayMap = new HashMap<String, String>();
            getPayMap.put("service", AlipayConfig.h5service);
            getPayMap.put("partner", AlipayConfig.partner);
            getPayMap.put("_input_charset", AlipayConfig.input_charset);
            getPayMap.put("notify_url", AlipayConfig.notify_url);
            getPayMap.put("out_trade_no", order_id);
            getPayMap.put("subject", product_name);
            getPayMap.put("payment_type", "1");
            getPayMap.put("seller_id", AlipayConfig.seller_id);
            getPayMap.put("total_fee", order_price);
            getPayMap.put("body", product_name);
            if (!("").equals(show_url) && null != show_url) {
                getPayMap.put("return_url", AlipayConfig.return_url);
                getPayMap.put("show_url", show_url);
                getPayMap.put("app_pay", "Y");
            }
            getPayMap = AlipayCore.paraFilter(getPayMap);
            String content = null;
            if (!("").equals(show_url) && null != show_url) {
                content = AlipayCore.createLinkString(getPayMap);//h5支付：参数=参数值
            } else {
                content = AlipayCore.createLinkStringPay(getPayMap);//app支付：参数="参数值"
            }
            String sign = RSA.sign(content, AlipayConfig.private_key, AlipayConfig.input_charset);
            if (("").equals(show_url) || null == show_url) {//app支付的sign签名，需要URLEncoder
                try {
                    sign = java.net.URLEncoder.encode(sign, "utf-8");
                } catch (UnsupportedEncodingException e) {
                    e.printStackTrace();
                }
                content = content + "&sign=\"" + sign + "\"&sign_type=\"" + AlipayConfig.sign_type + "\"";
            } else {
                getPayMap.put("sign", sign);
                getPayMap.put("sign_type", AlipayConfig.sign_type);
                List<String> keys = new ArrayList<String>(getPayMap.keySet());
                StringBuffer sbHtml = new StringBuffer();
                sbHtml.append("<form id=\"alipaysubmit\" name=\"alipaysubmit\" action=\"" + ALIPAY_GATEWAY_NEW + "_input_charset=" + AlipayConfig.input_charset + "\" method=\"post\">");

                for (int i = 0; i < keys.size(); i++) {
                    String name = (String) keys.get(i);
                    String value = (String) getPayMap.get(name);
                    sbHtml.append("<input type=\"hidden\" name=\"" + name + "\" value=\"" + value + "\"/>");
                }

                // submit按钮控件请不要含有name属性
                sbHtml.append("<input type=\"submit\" value=\"确认\" style=\"display:none;\"></form>");
                sbHtml.append("<script>document.forms['alipaysubmit'].submit();</script>");
                content = sbHtml.toString();
            }
            model.setModel(content);
            model.setCode("1");
        }
        return JSON.toJSONString(model);
    }

}
